// 高德地图配置和工具函数
export const MAP_CONFIG = {
  // 高德地图API Key
  key: '0c9a807ee106aa3d81087505920a86d1',
  // 高德地图Web API地址
  webApiUrl: 'https://restapi.amap.com/v3',
  // 高德地图JS API地址
  jsApiUrl: 'https://webapi.amap.com/maps',
  // 默认地图配置
  defaultOptions: {
    zoom: 10,
    center: [116.397428, 39.90923], // 北京坐标
    viewMode: '3D',
    pitch: 0,
    rotation: 0
  }
}

// 地图工具类
export class MapUtils {
  static instance = null
  
  constructor() {
    if (MapUtils.instance) {
      return MapUtils.instance
    }
    MapUtils.instance = this
    this.map = null
    this.markers = []
  }
  
  // 初始化地图
  async initMap(containerId, options = {}) {
    return new Promise((resolve, reject) => {
      // 检查是否已加载高德地图API
      if (typeof AMap === 'undefined') {
        this.loadMapScript().then(() => {
          this.createMap(containerId, options, resolve, reject)
        }).catch(reject)
      } else {
        this.createMap(containerId, options, resolve, reject)
      }
    })
  }
  
  // 加载高德地图脚本
  loadMapScript() {
    return new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = `${MAP_CONFIG.jsApiUrl}?v=2.0&key=${MAP_CONFIG.key}&callback=onMapReady`
      script.async = true
      
      window.onMapReady = () => {
        resolve()
      }
      
      script.onerror = () => {
        reject(new Error('高德地图加载失败'))
      }
      
      document.head.appendChild(script)
    })
  }
  
  // 创建地图实例
  createMap(containerId, options, resolve, reject) {
    try {
      const mapOptions = {
        ...MAP_CONFIG.defaultOptions,
        ...options
      }
      
      this.map = new AMap.Map(containerId, mapOptions)
      
      // 地图加载完成事件
      this.map.on('complete', () => {
        console.log('地图加载完成')
        resolve(this.map)
      })
      
      // 地图加载失败事件
      this.map.on('error', (error) => {
        console.error('地图加载失败:', error)
        reject(error)
      })
      
    } catch (error) {
      reject(error)
    }
  }
  
  // 获取当前位置
  getCurrentLocation() {
    return new Promise((resolve, reject) => {
      if (!this.map) {
        reject(new Error('地图未初始化'))
        return
      }
      
      this.map.plugin('AMap.Geolocation', () => {
        const geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 10000,
          maximumAge: 0,
          convert: true,
          showButton: false,
          showMarker: false,
          showCircle: false
        })
        
        geolocation.getCurrentPosition((status, result) => {
          if (status === 'complete') {
            const position = {
              longitude: result.position.lng,
              latitude: result.position.lat,
              address: result.formattedAddress
            }
            resolve(position)
          } else {
            reject(new Error('定位失败: ' + result.message))
          }
        })
      })
    })
  }
  
  // 添加标记
  addMarker(position, options = {}) {
    if (!this.map) {
      console.error('地图未初始化')
      return null
    }
    
    const marker = new AMap.Marker({
      position: [position.longitude, position.latitude],
      title: options.title || '',
      content: options.content || '',
      ...options
    })
    
    this.map.add(marker)
    this.markers.push(marker)
    
    return marker
  }
  
  // 清除所有标记
  clearMarkers() {
    if (this.markers.length > 0) {
      this.map.remove(this.markers)
      this.markers = []
    }
  }
  
  // 设置地图中心
  setCenter(longitude, latitude) {
    if (this.map) {
      this.map.setCenter([longitude, latitude])
    }
  }
  
  // 设置地图缩放级别
  setZoom(zoom) {
    if (this.map) {
      this.map.setZoom(zoom)
    }
  }
  
  // 搜索地点
  async searchPlace(keyword, city = '') {
    return new Promise((resolve, reject) => {
      if (!this.map) {
        reject(new Error('地图未初始化'))
        return
      }
      
      this.map.plugin('AMap.PlaceSearch', () => {
        const placeSearch = new AMap.PlaceSearch({
          city: city,
          pageSize: 20,
          pageIndex: 1
        })
        
        placeSearch.search(keyword, (status, result) => {
          if (status === 'complete' && result.poiList) {
            const places = result.poiList.pois.map(poi => ({
              id: poi.id,
              name: poi.name,
              address: poi.address,
              longitude: poi.location.lng,
              latitude: poi.location.lat,
              type: poi.type,
              tel: poi.tel
            }))
            resolve(places)
          } else {
            reject(new Error('搜索失败'))
          }
        })
      })
    })
  }
  
  // 计算距离
  calculateDistance(point1, point2) {
    if (typeof AMap !== 'undefined') {
      const distance = AMap.GeometryUtil.distance(
        [point1.longitude, point1.latitude],
        [point2.longitude, point2.latitude]
      )
      return Math.round(distance) // 返回米为单位的距离
    }
    return 0
  }
  
  // 销毁地图
  destroy() {
    if (this.map) {
      this.map.destroy()
      this.map = null
      this.markers = []
    }
  }
}

// 导出单例实例
export const mapUtils = new MapUtils() 